package com.uyayo.oms.common.controller;

import com.uyayo.framework.common.util.MD5Util;
import com.uyayo.framework.message.enums.ResultMsgEnum;
import com.uyayo.framework.web.constants.WebConstants;
import com.uyayo.framework.web.exception.CaptchaException;
import com.uyayo.framework.web.exception.CaptchaIsNullException;
import com.uyayo.framework.web.exception.CaptchaTimeOutException;
import com.uyayo.framework.message.model.Result;
import com.uyayo.framework.common.util.CookieUtils;
import com.uyayo.framework.web.util.VerifyCaptchaUtil;
import com.uyayo.oms.common.biz.HomeBiz;
import com.uyayo.oms.common.vo.LoginVO;
import com.uyayo.oms.shiro.ManagerUsernamePasswordToken;
import com.uyayo.oms.system.biz.ParamBiz;
import com.uyayo.system.config.service.SysParamService;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.validation.Errors;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * 
 * Title: LoginController
 * Description:登录的控制器
 * Company: www.lelekeji.com
 * @author 乐乐科技.胡逢君
 * @date 2016-4-23下午4:03:35
 * @version 1.0
 */
@Slf4j
@Controller
@RequestMapping("/oms")
public class LoginController{
	private final Logger logger = LoggerFactory.getLogger(this.getClass());

	private final HomeBiz homeBiz;

	private final SysParamService sysParamService;
	
	private final ParamBiz paramBiz;
	
	private final MessageSource messageSource;

	@Autowired
	public LoginController(HomeBiz homeBiz, SysParamService sysParamService, ParamBiz paramBiz, MessageSource messageSource) {
		this.homeBiz = homeBiz;
		this.sysParamService = sysParamService;
		this.paramBiz = paramBiz;
		this.messageSource = messageSource;
	}

	@RequestMapping(value="/login",method=RequestMethod.GET)
	public ModelAndView manager_login(ModelAndView modelAndView,HttpServletRequest request,String redirectURL,HttpSession session) {
		String MANAGER_LOGIN_PAGE = sysParamService.getSysParamValueByCode("MANAGER_LOGIN_PAGE");  	//管理员登录页面
		String MANAGER_INDEX = sysParamService.getSysParamValueByCode("MANAGER_INDEX");				//管理员首页

		if (redirectURL == null || redirectURL.equals("")){
			
			redirectURL = MANAGER_INDEX;
		}
		modelAndView.addObject("redirectURL", redirectURL);
		modelAndView.setViewName(paramBiz.getManagerTemplatesPrefix()+MANAGER_LOGIN_PAGE);
		return modelAndView;
	}
	
	@ResponseBody
	@RequestMapping(value="/login",method=RequestMethod.POST, produces = {MediaType.APPLICATION_JSON_VALUE})
	public Result manager_login(HttpServletRequest request, HttpServletResponse response,
								String redirectURL, @Validated LoginVO loginVO, Errors errors, HttpSession session) {
		
		String MANAGER_INDEX = sysParamService.getSysParamValueByCode("MANAGER_INDEX");				//管理员首页
		
		if (redirectURL == null || redirectURL.equals("")){
			redirectURL = MANAGER_INDEX;
		}
		
		if (errors.hasErrors()) {
			return Result.error(errors.getFieldError().getDefaultMessage());
	    }
		
		String captchaSession = (String) session.getAttribute(WebConstants.CAPTCHA_SESSION);
		Long captchaTimeSession = (Long) session.getAttribute(WebConstants.CAPTCHA_SESSION_TIME);
		String captcha = loginVO.getCaptcha();

		Subject subject = SecurityUtils.getSubject();
		String password_ = MD5Util.md5(loginVO.getPassword());
		ManagerUsernamePasswordToken token = new ManagerUsernamePasswordToken(loginVO.getLoginname(),password_,true,request.getLocalAddr());
        try {
			VerifyCaptchaUtil.verifyCaptcha(captcha,captchaSession,captchaTimeSession);
			subject.login(token);
			return Result.success(messageSource.getMessage(ResultMsgEnum.LOGIN_SUCCESS.getKey(),new Object[]{}, request.getLocale()),redirectURL);
		} catch (CaptchaException | CaptchaIsNullException e) {
			return Result.error(messageSource.getMessage(ResultMsgEnum.CAPTCHA_ERROR.getKey(),new Object[]{}, request.getLocale()));
		} catch (CaptchaTimeOutException e) {
			return Result.error(messageSource.getMessage(ResultMsgEnum.CAPTCHA_TIMEOUT.getKey(),new Object[]{}, request.getLocale()));
		} catch(UnknownAccountException uae){
			return Result.error(messageSource.getMessage(ResultMsgEnum.USERNAME_PASSWORD_ERROR.getKey(),new Object[]{}, request.getLocale()));
        }catch (IncorrectCredentialsException ice) {
			String message = messageSource.getMessage(ResultMsgEnum.LOGIN_FAIL.getKey(),new Object[]{}, request.getLocale());
        	log.error(message,ice);
			return Result.error(400,message);
        }catch (AuthenticationException e) {
            token.clear();
			String message = messageSource.getMessage(ResultMsgEnum.AUTH_FAIL.getKey(),new Object[]{}, request.getLocale());
			log.error(message,e);
			return Result.error(400,message);
        }catch (Exception e) {
			String message = messageSource.getMessage(ResultMsgEnum.INTERNAL_SERVER_ERROR.getKey(),new Object[]{}, request.getLocale());
			logger.error(message,e);
			return Result.error(ResultMsgEnum.INTERNAL_SERVER_ERROR.code(),message);
		}finally {
			request.getSession().removeAttribute(WebConstants.CAPTCHA_SESSION);
			request.getSession().removeAttribute(WebConstants.CAPTCHA_SESSION_TIME);
		}
	}

	/**
	 * 注销系统
	 * @param response
	 * @param request
	 * @param session
	 * @return
	 */
	@ResponseBody
	@RequestMapping("logout")
	public Result logout(HttpServletRequest request,HttpServletResponse response,HttpSession session){
		Result customResult = new Result();
		
		Subject subject = SecurityUtils.getSubject();

		
		String lOGIN_SSO = sysParamService.getSysParamValueByCode("LOGIN_SSO");

		if (lOGIN_SSO.equals("1")) {
			String token = CookieUtils.getCookieValue(request, "TT_TOKEN");
			if(token==null){
				customResult.setStatus(200);
				customResult.setMessage("注销成功！");
			}else{
				//根据token换取用户信息，调用sso系统的接口。
				customResult = homeBiz.logoutUserByToken(token);
				if(customResult.getStatus()==200){
					CookieUtils.deleteCookie(request, response, "TT_TOKEN");
				}
			}
		}else{
			try {
				subject.logout();//退出登录操作
			} catch (IllegalStateException e) {
				
			}
			
			customResult.setStatus(200);
			customResult.setMessage("注销成功！");
			
		}
		return customResult;
	}
}
